package com.example.arithmeticleetcode.leetcode.July;

import java.util.*;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-07-31 09:52
 **/
public class Demo13 {

    public static void main(String[] args) {
        //points = [[1,3],[-2,2]], K = 1
        int[][] points1 = {{1, 3}, {-2, 2}};
        int K1 = 1;
        System.out.println(Arrays.asList(kClosest(points1, K1)));
        //points = [[3,3],[5,-1],[-2,4]], K = 2
        int[][] points2 = {{3, 3}, {5, -1}, {-2, 4}};
        int K2 = 2;
        System.out.println(Arrays.asList(kClosest(points2, K2)));
    }

    public static int[][] kClosest(int[][] points, int K) {
        Map<Integer, List<int[]>> map = new HashMap<>();
        List<Integer> keyList = new ArrayList<>();
        for (int[] point : points) {
            Integer key = point[0] * point[0] + point[1] * point[1];
            if (map.containsKey(key)) {
                List<int[]> list = map.get(key);
                list.add(point);
                map.put(key, list);
            } else {
                List<int[]> list = new ArrayList<>();
                list.add(point);
                map.put(key, list);
            }
            keyList.add(key);
        }
        Collections.sort(keyList, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        System.out.println(map);
        System.out.println(keyList);
        int[][] result = new int[K][];
        int count = 0;
        for (int i = 0; i < K; i++) {
            List<int[]> list = map.get(keyList.get(i));
            for (int[] ints : list) {
                result[count] = ints;
                System.out.println(ints[0] + "========" + ints[1]);
                count++;
                if (count >= K) {
                    return result;
                }
            }
        }
        return result;
    }
}
